package com.linran.webjsonrsp.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * @author lin
 * @date 2020-06-03 15:11
 * <p>
 * urlEncode后的文件名，只有通过浏览器下载才能正常显示名称；postman下载也会是code后的名称
 */
@Slf4j
@Controller
@RequestMapping("download")
public class FileDownloadController {

    /**
     * 二进制文件通用下载方案
     * <p>
     * Content-Type: application/octet-stream
     * Content-Disposition: attachment; filename=%E4%BA%8C%E8%BF%9B%E5%88%B6%E6%B5%81%E4%B8%8B%E8%BD%BDexcel%E6%96%87%E4%BB%B6.xlsx
     */
    @GetMapping("common")
    public ResponseEntity<byte[]> downloadCommonFile() throws IOException {
        File excelFile = null;
        try {
            excelFile = new File("F:\\study\\lin_module\\web-json-rsp\\src\\main\\resources\\测试.xlsx");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="
                    + URLEncoder.encode("二进制流下载excel文件.xlsx", StandardCharsets.UTF_8.toString()));
            return new ResponseEntity<>(FileCopyUtils.copyToByteArray(excelFile), headers, HttpStatus.OK);
        } finally {
            Optional.ofNullable(excelFile).ifPresent(File::deleteOnExit);
        }
    }

    /**
     * 标准excel文件下载
     * <p>
     * Content-Type: application/vnd.ms-excel
     * Content-Disposition: attachment; filename=%E6%99%AE%E9%80%9Aexcel%E6%96%87%E4%BB%B6.xlsx
     */
    @GetMapping("excel")
    public void downloadExcel(HttpServletResponse response) throws IOException {
        File excelFile = null;
        try {
            excelFile = new File("F:\\study\\lin_module\\web-json-rsp\\src\\main\\resources\\测试.xlsx");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="
                    + URLEncoder.encode("普通excel文件.xlsx", StandardCharsets.UTF_8.toString()));
            response.getOutputStream().write(FileCopyUtils.copyToByteArray(excelFile));
        } finally {
            Optional.ofNullable(excelFile).ifPresent(File::deleteOnExit);
        }
    }

    /**
     * 多部分主体header下载
     * a header for a multipart body
     * <p>
     * Content-Type: application/vnd.ms-excel
     * Content-Disposition: form-data; name="fieldName"; filename="filename.jpg"
     */
    @GetMapping("multipart")
    public ResponseEntity<byte[]> downloadExcelBuMultiPart() {
        File excelFile = null;
        try {
            excelFile = new File("F:\\study\\lin_module\\web-json-rsp\\src\\main\\resources\\测试.xlsx");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
            headers.setContentDispositionFormData("fieldName", URLEncoder.encode("普通excel文件.xlsx", StandardCharsets.UTF_8.toString()));
            //正常文件下载返回
            return new ResponseEntity<>(FileCopyUtils.copyToByteArray(excelFile), headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            Optional.ofNullable(excelFile).ifPresent(File::deleteOnExit);
        }
        //如果try中没有返回内容，则此处返回空内容
        return new ResponseEntity<>(new byte[0], HttpStatus.INTERNAL_SERVER_ERROR);
    }
}